package com.solocredit.finance.ui.main.impl

import android.content.Context
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.BaseFragment
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.main.fm.MullaCouponFm
import com.solocredit.finance.ui.main.fm.MullaHomeFm
import com.solocredit.finance.ui.main.fm.MullaRepayFm
import com.solocredit.finance.ui.main.fm.MullaUserFm
import com.solocredit.finance.ui.main.view.IMullaMainView
import com.solocredit.finance.utils.DateUtils
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaSignRiseHelper
import com.solocredit.finance.utils.helper.MullaUserCouponHelper
import com.solocredit.finance.utils.helper.MullaUserPointsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 15:46
 * @Annotation：主页面 Presenter 实现
 */
class MullaMainPresenterImpl(context: Context?) : MvpPresenter<IMullaMainView>(context) {
    //val 是不可变的 var 可变的
    private val tabImageNormal = arrayListOf(
        R.mipmap.mulla_tab_home_normal,
        R.mipmap.mulla_tab_repayment_normal,
        R.mipmap.mulla_tab_coupon_normal,
        R.mipmap.mulla_tab_user_normal
    )

    private val tabImageSelect = arrayListOf(
        R.mipmap.mulla_tab_home_selected,
        R.mipmap.mulla_tab_repayment_selected,
        R.mipmap.mulla_tab_coupon_selected,
        R.mipmap.mulla_tab_user_selected
    )

    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()
    private val fragments = ArrayList<BaseFragment>()
    private var curtIndex = 0

    /**
     * 加载Tabbar数据
     */
    fun loadMullaTabList(){
        tabList.clear()
        //tab
        for (i in 0 until tabImageNormal.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabImageSelected", tabImageSelect[i])
            tabObj.put("tabImageNormal", tabImageNormal[i])
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        mvpView?.showMullaTabList(tabList)
    }

    /**
     * 加载FragmentList
     */
    fun loadMullaFragmentList(){
        fragments.add(MullaHomeFm())//首页
        fragments.add(MullaRepayFm())//还款
        fragments.add(MullaCouponFm())//优惠券
        fragments.add(MullaUserFm())//个人中心

        mvpView?.showMullaLoading()
        //获取产品列表，判断是否有待还款产品
        loadMullaProductListAction(true)
    }

    /**
     * 切换Tab
     */
    fun setMullaCurrentItemIndex(index: Int) {
        curtIndex = index
        if (curtIndex < 0){
            curtIndex = 0
        }
        for (tabObj in tabList) {
            when (tabObj.optInt("tabId")) {
                curtIndex -> {
                    tabObj.put("isSelect", true)
                }
                else -> {
                    tabObj.put("isSelect", false)
                }
            }
        }
        mvpView?.notifyTabDataChanged()

        val fragment = fragments[curtIndex]
        mvpView?.showMullaFragment(fragment,curtIndex)

        //切换Tab需要刷新签到信息 获取积分
        loadMullaUserSignInfoAction()
        //获取优惠券信息
        MullaUserCouponHelper.loadMullaUserCouponListAction()
    }

    /**
     * 获取总流程
     */
    fun loadMullaProcessAction() {
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_PROCESS_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_PROCESS_PATH)
        }
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code",0)) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //保存用户流程状态
                        if (obj != null) {
                            // TODO: 测试添加 Step 类型
//                            val allStepTitles = obj.optJSONArray("allStepTitles")
//                            allStepTitles.put("Ocr Info")
//                            allStepTitles.put("Face recognition")
//                            allStepTitles.put("Account Info")
//                            val allSteps = obj.optJSONArray("allSteps")
//                            allSteps.put("ocr_info")
//                            allSteps.put("sefie_info")
//                            allSteps.put("account_info")
//                            val steps = obj.optJSONArray("steps")
//                            steps.put("ocr_info")
//                            steps.put("sefie_info")
//                            val index = Random.nextInt(3)
//                            when(index){
//                                0 -> {
//                                    steps.put("ocr_info")
//                                }
//                                1 -> {
//                                    steps.put("sefie_info")
//                                }
//                                else -> {
//                                    steps.put("account_info")
//                                }
//                            }
                            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PROCESS, obj.toString())
                            //通知全局流程刷新完成
                            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PROCESS_REFRESHED))

                            // TODO: 根据 smsFlag 或 whatsappFlag 判断是否需要校验手机号
                            val smsFlag = obj.optString("smsFlag") == "YES"
                            val whatsappFlag = obj.optString("whatsappFlag") == "YES"
                            if (smsFlag or whatsappFlag){//需要校验手机号
                                mvpView?.ShowMullaVerificationPage()
                            }
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showMullaNetworkErrorDialog("Mian Page Get UserProcess", onRetryClick = {
                        loadMullaProcessAction()
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取签到信息
     * signType:
     *          getSignInfo - 查询用户签到信息
     *          userSignIn - 保存用户签到信息
     */
    fun loadMullaUserSignInfoAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_SIGN_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE))
            put("signType","getSignInfo")
        }
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            obj.put("lastSignTime",obj.optString("lastSignTime").replace("-",""))
                            //保存用户签到信息
                            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_SIGN_INFO,obj.toString())
                            //刷新积分完成
                            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_POINTS_REFRESHED))

                            //上次签到时间
                            val lastSignTime = obj.optString("lastSignTime")
                            //连续签到天数
                            val conSignTime = obj.optString("conSignTime")

                            //没有签到时间 - 没有签过到
                            if (lastSignTime.isEmpty() || "0" == lastSignTime){
                                saveMullaUserSignAction("1")
                            } else {
                                //签过到
                                //上次签到时间是否是今天
                                if (DateUtils.IsToday(lastSignTime.toLong() * 1000)){
                                    //签过到了
                                    /**
                                     * TODO: 2025/05/26-2025/05/30 赞比亚更新新需求，增加签到提额逻辑
                                     */
                                    MullaSignRiseHelper.onMullaHandleSignRiseData(mvpView?.getContext())
                                } else {
                                    //上次签到时间是否是昨天
                                    if (DateUtils.IsYesterday(lastSignTime.toLong() * 1000)){
                                        //连续签到天数 +1
                                        saveMullaUserSignAction("${conSignTime.toInt() + 1}")
                                    } else {
                                        //非连续签到： 连续签到天数 1
                                        saveMullaUserSignAction("1")
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 签到
     */
    fun saveMullaUserSignAction(conSignTime: String){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_SIGN_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE))
            put("signType","userSignIn")
            put("signDate", System.currentTimeMillis() / 1000)//签到时间戳
            put("conSignTime", conSignTime)//连续签到天数
        }
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            // 连续签到增加积分数
                            val signPoints = MullaCustomConfigsHelper.getMullaSignPointsBySignTime(conSignTime.toInt())
                            //弹窗签到成功dialog
                            mvpView?.showMullaSignSuccessDialog(signPoints)
                            //签到成功 存储签到积分
                            mvpView?.getContext()?.let { context ->
                                MullaUserPointsHelper.saveMullsUserPointsAction("signPoints",context.getString(R.string.points_use_info_check_in),signPoints)
                            }
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取产品列表
     * 存在待还款的产品 ，需要直接展示Repay，否则显示可申请产品列表
     */
    fun loadMullaProductListAction(isCheck: Boolean = false){
        val params = JSONObject()
            .addCommonParams()
            .addRandomParams()
            .apply {
                put("mobile", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE))
                put("env", "dev")
                put("showDailyIncrease",true)
            }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_PRODUCT_LIST_PATH)
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                var showTabIndex = 0
                when(data.optInt("code")) {
                    0 -> {//成功
                        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PRODCTS,data.optString("obj"))
                        MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PRODUCT_REFRESHED))

                        val objArray = data.optJSONArray("obj")
                        if (objArray != null) {
                            //可申请的产品数量
                            var productCount = 0
                            for (i in 0..<objArray.length()){
                                val item = objArray.optJSONObject(i)
                                //可申请的产品
                                if (item.optString("activeFlag") == "YES"){
                                    productCount++
                                }

                                //待还款的产品
                                if ("REPAYMENT" == item.optString("status")){
                                    showTabIndex = 1
                                }
                            }
                            //保存用户VIP等级
                            saveMullaUserVip(productCount)
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
                if (isCheck){
                    //默认选中第1个
                    setMullaCurrentItemIndex(showTabIndex)
                }
            }

            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showMullaNetworkErrorDialog("Mian Page Get ProductList", onRetryClick = {
                        mvpView?.showMullaLoading()
                        loadMullaProductListAction(isCheck)
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PRODUCT_FINISHED))
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 保存用户Vip等级
     */
    fun saveMullaUserVip(pCount: Int){
        if (pCount <= 1){
            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_VIP,1)
        } else if (pCount > 4){
            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_VIP,3)
        } else {
            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_VIP,2)
        }
    }
}